package org.lfh.wintersun.web;

import jakarta.annotation.Resource;
import org.lfh.wintersun.common.result.CommonResult;
import org.lfh.wintersun.utils.JwtUtil;
import org.lfh.wintersun.web.user.dto.LoginRequest;
import org.lfh.wintersun.web.user.entity.SysUserEntity;
import org.lfh.wintersun.web.user.service.SysUserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class AuthController {

    @Resource
    private SysUserService userService;
    @Resource
    private JwtUtil jwtUtil;

    @PostMapping("/register")
    public CommonResult<?> register(@RequestBody SysUserEntity user) {
        // 加密密码并保存用户
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        userService.save(user);
        return CommonResult.success();
    }

    @PostMapping("/login")
    public CommonResult<String> login(@RequestBody LoginRequest loginRequest) {
        SysUserEntity user = userService.findByUsername(loginRequest.getUserName());
        if (user != null && new BCryptPasswordEncoder().matches(loginRequest.getPassWord(), user.getPassword())) {
            return CommonResult.success(jwtUtil.generateToken(user.getLoginName()));
        }
        throw new RuntimeException("用户名或密码错误");
    }
}
